#include "GameWorld.hpp"
#include <algorithm>

using namespace Typhoon;

GameWorld::GameWorld() {
}


GameWorld::~GameWorld() {
}

void GameWorld::AddSystem( GameSystem* system ) {
	gameSystems.push_back(system);
	for(int i=0; i<gameObjects.size(); i++) {
		system->AddGameObject(gameObjects[i]);
	}
	GameSystem::SubSystems& subSystems = system->GetSubSystems();
	for(int i=0; i<subSystems.size(); i++) {
		AddSystem(subSystems[i]);
	}
}

void GameWorld::RemoveSystem( GameSystem* system ) {
	GameSystems::iterator it = std::find(gameSystems.begin(), gameSystems.end(), system);
	if (it==gameSystems.end()) return; 
	gameSystems.erase(it);
	system->Remove();
	GameSystem::SubSystems& subSystems = system->GetSubSystems();
	for(int i=0; i<subSystems.size(); i++) {
		RemoveSystem(subSystems[i]);
	}
}


void GameWorld::AddGameObject( GameObject* gameObject ) {
	gameObjects.push_back(gameObject);
	ComponentAdded(gameObject);
	gameObject->ComponentAdded += event_handler(this, &GameWorld::ComponentAdded);
}

void GameWorld::RemoveGameObject( GameObject* gameObject ) {
	GameObjects::iterator it = std::find(gameObjects.begin(), gameObjects.end(), gameObject);
	if (it==gameObjects.end()) return; 
	gameObjects.erase(it);
	gameObject->RemovedFromWorld(gameObject);
	gameObject->ComponentAdded -= event_handler(this, &GameWorld::ComponentAdded);
}

void GameWorld::ComponentAdded( GameObject* gameObject ){
	for(int i=0; i<gameSystems.size(); i++) {
		GameSystem* system = gameSystems[i];
		if (!system->ContainsGameObject(gameObject)) {
			system->AddGameObject(gameObject);
		}
	}
}
